package com.zjmzxfzhl.modules.purchase.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zjmzxfzhl.common.base.BaseServiceImpl;
import com.zjmzxfzhl.common.exception.AppException;
import com.zjmzxfzhl.common.exception.BaseException;
import com.zjmzxfzhl.common.util.PathUtil;
import com.zjmzxfzhl.common.util.bs.PurchaseUtils;
import com.zjmzxfzhl.modules.purchase.controller.dto.PurchaseOrderDetailDto;
import com.zjmzxfzhl.modules.purchase.controller.vo.PurchaseOrderDetailVo;
import com.zjmzxfzhl.modules.purchase.controller.vo.PurchaseProjectVo;
import com.zjmzxfzhl.modules.purchase.entity.PurchaseOrderDetail;
import com.zjmzxfzhl.modules.purchase.entity.PurchaseProject;
import com.zjmzxfzhl.modules.purchase.mapper.PurchaseOrderDetailMapper;
import com.zjmzxfzhl.modules.purchase.mapper.PurchaseProjectMapper;
import com.zjmzxfzhl.modules.purchase.service.PurchaseOrderDetailService;
import com.zjmzxfzhl.modules.purchase.service.PurchaseProjectService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;

/**
 * Service
 *
 * @author 庄金明
 */
@Service
public class PurchaseProjectServiceImpl extends BaseServiceImpl<PurchaseProjectMapper, PurchaseProject>
        implements PurchaseProjectService {

    @Autowired
    private PurchaseOrderDetailService detailService;

    @Autowired
    private PurchaseOrderDetailMapper detailMapper;

    @Override
    public IPage<PurchaseProjectVo> list(IPage<PurchaseProjectVo> page, PurchaseProject purchaseProject) {
        List<PurchaseProjectVo> projectVoList = baseMapper.list(page, purchaseProject);
        if (!CollectionUtils.isEmpty(projectVoList)) {
            for (PurchaseProjectVo projectVo : projectVoList) {
                fillDetailVo(projectVo);
            }
        }
        return page.setRecords(projectVoList);
    }

    private void fillDetailVo(PurchaseProjectVo projectVo) {
        PurchaseOrderDetailDto dto = new PurchaseOrderDetailDto();
        dto.setProjectId(projectVo.getId());
        List<PurchaseOrderDetailVo> detailVos = detailService.listBy(dto);

        if (!CollectionUtils.isEmpty(detailVos)) {
            projectVo.setDetails(detailVos);
            BigDecimal totalAmount = new BigDecimal(0);
            for (PurchaseOrderDetailVo detailVo : detailVos) {
                totalAmount = totalAmount.add(detailVo.getMaterialTotalPrice());
            }
            projectVo.setProjectAmount(totalAmount);
        } else {
            projectVo.setProjectAmount(new BigDecimal(0));
        }
    }

    @Override
    public PurchaseProject validPurchaseProject(PurchaseProject project) {
        if (StringUtils.isEmpty(project.getProjectName())) {
            project.setProjectName("备用");
        }
        if (!StringUtils.isEmpty(project.getProjectName())) {
            PurchaseProject filter = new PurchaseProject();
            filter.setProjectName(project.getProjectName());
            PurchaseProject dbProject = this.getOne(new QueryWrapper<>(filter));
            if (null == dbProject) {
                this.save(project);
                return project;
            }
            return dbProject;
        } else {
            throw new AppException("缺少项目名称");
        }
    }

    @Override
    public void deleteProjects(List<Long> ids) {
        for (Long projectId : ids) {
            PurchaseOrderDetail filter = new PurchaseOrderDetail();
            filter.setProjectId(projectId);
            List<PurchaseOrderDetail> details = detailService.list(new QueryWrapper<>(filter));
            if (!CollectionUtils.isEmpty(details)) {
                throw new AppException("存在关联的审批单：" + details.get(0).getOrderId());
            }
        }
        this.removeByIds(ids);
    }

    @Override
    public File exportDetail(Long projectId) {
        //查询所有相关内容
        PurchaseProject project = this.getById(projectId);
        if (null == project) {
            throw new BaseException("项目不存在：" + projectId);
        }
        PurchaseProjectVo projectVo = BeanUtil.copyProperties(project, PurchaseProjectVo.class);
        fillDetailVo(projectVo);
        File exportFile = null;
        try {
            ClassPathResource templateFileResource = new ClassPathResource("templates/project-template.xls");
            exportFile = PathUtil.getTempFile(project.getProjectName() + "_.xls");
            FileUtils.copyInputStreamToFile(templateFileResource.getInputStream(), exportFile);
            PurchaseUtils.exportPurchaseProject(projectVo, exportFile);
        } catch (Exception e) {
            throw new AppException("文件读取失败" + e.getMessage());
        }
        return exportFile;
    }

    @Override
    public void replaceProjects(List<Long> oids, Long nid) {
        for (Long oid : oids) {
            this.replaceProjectId(oid, nid);
            //删除 多余project
            this.removeById(oid);
        }
    }

    public void replaceProjectId(Long oId, Long nId) {
        PurchaseOrderDetail detailFilter = new PurchaseOrderDetail();
        detailFilter.setProjectId(oId);
        List<PurchaseOrderDetail> details = detailMapper.selectList(new QueryWrapper<>(detailFilter));
        if (!CollectionUtils.isEmpty(details)) {
            for (PurchaseOrderDetail detail : details) {
                detail.setProjectId(nId);
                this.detailMapper.updateById(detail);
            }
        }
    }

}
